//
//  NLLiveTimerLabel.swift
//  NLNetworkSchool
//
//  Created by st on 2018/12/28.
//  Copyright © 2018 JQ. All rights reserved.
//

import UIKit

class NLLiveTimerLabel: UILabel {
    
    // MARK: 1.lift cycle
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        self.font = UIFont.systemFont(ofSize: 11)
        self.textColor = .white
        self.textAlignment = .center
    }

    convenience init(frame: CGRect, isStartTimer:Bool = true) {
        self.init(frame: frame)
        self.isStartTimer = isStartTimer
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        removeTimer()
    }
    // MARK: 2.private methods
    fileprivate func removeTimer() {
        if codeTimer != nil {
            codeTimer?.cancel()
            codeTimer = nil
        }
    }
    
    @objc func refreshTime() {
        guard let endTime = endTime else { return }
        let nowDate = Date.getCurrentDate()
        let endDate = endTime.timestampWithDate()
        let calendar = NSCalendar.current
        let components = calendar.dateComponents([.hour, .minute, .second], from: nowDate, to: endDate)
        guard let hour = components.hour,
            let minute = components.minute,
            let second = components.second else { return }
        
        if hour < 0 || minute < 0 || second < 0  {
            removeTimer()
            self.text = "0"
        }else{
            self.text = "\(hour.keepInt())" + ":" + "\(minute.keepInt())" + ":" +  "\(second.keepInt())"
        }
    }
    // MARK: 3.event response
    
    // MARK: 4.interface
    open var endTime:Double? {
        didSet {
            if isStartTimer == true {
                if codeTimer != nil { return }
                
                let queue = DispatchQueue.global()
                codeTimer = DispatchSource.makeTimerSource(queue: queue)
                codeTimer?.schedule(wallDeadline: .now(), repeating: .seconds(1))
                codeTimer?.setEventHandler { [weak self] in
                    DispatchQueue.main.async(execute: {
                        self?.refreshTime()
                    })
                }
                codeTimer?.resume()
            } else {
                refreshTime()
            }
        }
    }

    // 定时器
    fileprivate var codeTimer:DispatchSourceTimer?
    // 是否启动定时器
    var isStartTimer = true
}
